package com.example.park2212.user

import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.lib_base.mvvm.BaseActivity
import com.example.park2212.databinding.ActivityLoginBinding
import dagger.hilt.android.AndroidEntryPoint

@Route(path = "/app/user/LoginActivity")
@AndroidEntryPoint
class LoginActivity :BaseActivity<ActivityLoginBinding,UserViewModel> () {
    override fun initView() {
        binding.btnLogin.setOnClickListener {
            val username = binding.etUsername.text.toString()
            val password = binding.etPassword.text.toString()
            if (username.isNullOrEmpty() || password.isNullOrEmpty()){
                ToastUtils.showLong("输入不能为空")
                return@setOnClickListener
            }
            if (!password.matches(Regex("[A-z0-9_]{2,8}"))){
                ToastUtils.showLong("账号格式不正确")
                return@setOnClickListener
            }
            viewModel.login(username,password)
        }

        binding.newRegister.setOnClickListener {
            ARouter.getInstance().build( "/app/user/RegisterActivity").navigation()
        }
        val token = SPUtils.getInstance().getString("token","")
        if (token.isNotEmpty()){
            ARouter.getInstance().build("/app/MainActivity").navigation()
            finish()
        }
    }

    override fun initData() {
        viewModel.loginSuccess.observe(this){
            ToastUtils.showLong("登录成功")
            SPUtils.getInstance().apply {
                put("token",it.token)
                put("username",it.username)
                put("accountid",it.id)
            }
            if (it.roleid == 2){
                ARouter.getInstance().build("/app/MainActivity").navigation()
            }else{
                ARouter.getInstance().build("/app/WebViewActivity").navigation()
            }

        }

    }

}